/* eslint-disable */
<template>
	<!-- 批量分配角色权限 -->
	<div>
		<el-dialog class="handleDialog" :title="title" :visible.sync="show" width="60%" :close-on-click-modal="false" @close="closeDiolag">
			<el-row>
				<el-form :rules="rules" :inline="false" :model="dataForm" ref="dataForm" label-width="110px">
					<el-row>
						<el-col :span="18">
							<span style="font-weight:bold;">{{$t('components.handleResourceBatch.step1')}}：</span>{{$t('components.handleResourceBatch.selectByAccountTip')}}
						</el-col>
						<!--操作按钮-->
						<el-col :span="6" class="alignC">
							<el-button size="small" type="primary" @click="addAccountVisible=true;accountText='';accountTextList=[]">{{$t('components.handleResourceBatch.batchAdd')}}</el-button>
							<el-button size="small" type="danger" @click="removeSelect">{{$t('components.handleResourceBatch.batchDelete')}}</el-button>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<el-table v-loading="loadind1" ref="datatableList" :data="datatableList" border max-height="500" style="width: 100%" @selection-change="selectAddListChange">
								<el-table-column type="selection" width="55"></el-table-column>
								<el-table-column prop="byAccountName" :label="$t('common.byUserName')+':'" show-overflow-tooltip></el-table-column>
								<el-table-column prop="empName" :label="$t('components.handleResourceBatch.empName')+':'" show-overflow-tooltip> </el-table-column>
								<el-table-column prop="positionName" :label="$t('common.positionName')+':'" show-overflow-tooltip> </el-table-column>
								<el-table-column prop="orgName" :label="$t('common.orgName')+':'" show-overflow-tooltip> </el-table-column>
								<el-table-column prop="netCode" :label="$t('common.netCode')+':'" show-overflow-tooltip> </el-table-column>
							</el-table>
							<p>{{$t('components.handleResourceBatch.totalCounts')}}:
								<span class="addtionTableSpan">{{datatableList.length}}</span>
								<span style="color:red;font-size:12px;" v-if="datatableList.length>200">({{$t('components.handleResourceBatch.overflowTip')}})</span>
							</p>
						</el-col>
					</el-row>
					<p><span style="font-weight:bold;">{{$t('components.handleResourceBatch.step2')}}：</span>{{$t('components.handleResourceBatch.selectGatagroup')}}</p>
					<el-row>
						<el-col :span="8" v-if="isSwitchRole==1">
							<el-form-item :label="$t('common.subsysName')+':'" prop="subsysName">
								<el-select v-model="dataForm.subsysName" :placeholder="$t('common.selectPlaceholder')">
									<el-option @click.native="handleSelectSubsys(item)" v-for="(item,index) in subsysTemOptions" :key="index" :label="item.label" :value="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8" v-if="isSwitchRole==1">
							<el-form-item :label="$t('common.roleName')+':'" prop="roleName">
								<el-select v-model="dataForm.roleName" :placeholder="$t('common.selectPlaceholder')" clearable :filter-method="getroleList">
									<el-option @click.native="dataForm.resourceName='';resourceOptionsFun('')" v-for="(item,index) in roleNameOptions" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item :label="$t('common.resourceName')+':'" prop="resourceName">
								<el-select v-model="dataForm.resourceName" filterable :placeholder="$t('common.selectPlaceholder')" :filter-method="resourceOptionsFun">
									<el-option @click.native="handleSelectResource(item)" v-for="item in resourceOptions" :key="item.code" :label="item.label" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col>
							<el-col :span="12" style="max-width: 320px;">
								<el-form-item :label="$t('common.dataGroupType')+':'" prop="dataGroupType">
									<el-radio-group v-model="dataForm.dataGroupType" @change="dataForm.dataGroupName='';dataGroupNameOptionsFun('')">
										<el-radio label="1">{{$t('components.handleResourceBatch.preAssignDataGroup')}}</el-radio>
										<el-radio label="2" v-if="dataForm.customDatagroup!=0 && dataForm.ownerSysId==dataForm.systemId">{{$t('components.handleResourceBatch.autoDefined')}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="6" style="margin-left: 20px;" v-if="dataForm.dataGroupType!=2">
								<el-select v-if="dataForm.dataGroupType!=2" v-model="dataForm.dataGroupName" filterable :placeholder="$t('common.selectPlaceholder')" :filter-method="dataGroupNameOptionsFun">
									<el-option v-for="item in dataGroupArr" :key="item.id" :label="item.label" :value="item.id">
									</el-option>
								</el-select>
							</el-col>
							<el-col :span="12" v-if="dataForm.dataGroupType==2">
								<span v-if="dataForm.dataGroupType==2"> <el-button  style="margin:0 10px;" size="small" type="primary" @click="autoDefined">{{$t('components.handleResourceBatch.autoDefinedAccess')}}</el-button></span>
							</el-col>
						</el-col>
					</el-row>
					<p><span style="font-weight:bold;">{{$t('components.handleResourceBatch.step3')}}：</span>{{$t('components.handleResourceBatch.maintainDate')}}</p>
					<el-row>
						<el-col :span="24">
							<el-form-item :label="$t('common.startTm')+':'" class="is-required" :class="(showError && !dataForm.startTm)?'is-error':''">
								<el-date-picker @change="checkDateValid('startTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd" v-model="dataForm.startTm" type="date" :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleResourceBatch.completionStartTime')}}）</span>
								<div class="el-form-item__error" v-if="showError && !dataForm.startTm">
									{{$t('validateWornText.slectStartTm')}}
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t('common.endTm')+':'" class="is-required" :class="(showError && !dataForm.endTm)?'is-error':''">
								<el-date-picker @change="checkDateValid('endTm') " :picker-options="pickerOptions1" value-format="yyyy-MM-dd" v-model="dataForm.endTm" type="date" :placeholder="$t('common.selectDate')"> </el-date-picker><span class="desc">（{{$t('components.handleResourceBatch.completionStartTime')}}）</span>
								<div class="el-form-item__error" v-if="showError && !dataForm.endTm">
									{{$t('validateWornText.slectEndTm')}}
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button @click="$emit('exit') ">{{$t('common.giveUp')}}</el-button>
				<el-button type="primary" @click="save">{{$t('common.save')}}</el-button>
			</div>
		</el-dialog>
		<!--批量添加账号-->
		<el-dialog class="newlyForm" :title="$t('components.handleResourceBatch.batchAdd')" :visible.sync="addAccountVisible" width="50%" :close-on-click-modal="false">
			<el-row>
				<p>{{$t('components.handleResourceBatch.inputByAccount')}}</p>
				<el-input @blur="getFocusVisible=false " @change="getFocusChange" v-if="getFocusVisible" :maxlength="2000" type="textarea" :rows="8" v-model="accountText"></el-input>
				<div style="min-height:180px;overflow: auto;" class="el-textarea__inner" @click="getFocusVisible=true" v-if="!getFocusVisible">
					<span :keys="index" :key="index" v-for="(item,index) in accountTextList"><span :class="item.flag? 'normalText':'errorText'">{{item.label}}</span><span v-if="index!=accountTextList.length-1">,</span></span>
				</div>
				<div style="margin-top: 5px;">{{$t('components.handleResourceBatch.supportMatAccount') }}</div>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addAccountVisible=false;">{{$t('common.giveUp')}}</el-button>
				<el-button type="primary" @click="saveAccount">{{$t('common.save')}}</el-button>
			</div>
		</el-dialog>
		<custom-datagroup :visible="autoDefinedVisible" @customDialogClose="autoDefinedVisible=false" @customDialogSave="customDialogSave" :formInfo="dataForm"></custom-datagroup>

	</div>
</template>

<script>
	import customDatagroup from './customDatagroup'
	import {
		Message,
		Notification,
		MessageBox,
		Loading
	} from 'element-ui'
	export default {
		name: 'handleRole',
		props: [
			'visible'
		],
		components: {
			customDatagroup
		},
		data() {
			return {
				show: false,
				dataForm: {
					subsysName: '',
					roleName: '',
					resourceName: '',
					endTm: '',
					startTm: '',
					dataGroupName: '',
					dataGroupType: '1'
				},
				pickerOptions1: {
					disabledDate(time) {
						return(time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000)
					}
				},
				rules: {
					roleName: [{
						required: true,
						message: this.$t('validateWornText.selectRoleName'),
						trigger: 'change'
					}],
					subsysName: [{
						required: true,
						message: this.$t('validateWornText.selectSubsysName'),
						trigger: 'change'
					}],
					resourceName: [{
						required: true,
						message: this.$t('validateWornText.selectResourceName'),
						trigger: 'change'
					}],
					dataGroupName: [{
						required: true,
						message: this.$t('validateWornText.selectDataGroupName'),
						trigger: 'change'
					}],
					dataGroupType: [{
						required: true,
						message: this.$t('validateWornText.selectDataGroupType'),
						trigger: 'change'
					}]
				},
				roleNameOptions: [],
				subsysTemOptions: [],
				datatableList: [],
				title: '',
				loadind1: false,
				addSelectMultipleSelection: [],
				showError: false,
				addAccountVisible: false,
				accountText: '',
				accountTextList: [],
				getFocusVisible: true,
				resourceOptions: '',
				autoDefinedVisible: false,
				dataGroupArr: [],
				systemInfo: {},
				isSwitchRole: ''
			}
		},
		watch: {
			visible: 'visibleChange'
		},
		mounted() {
			this.searchSystemInfo()
			this.resourceOptionsFun('')
		},
		methods: {
			async searchSystemInfo() {
				this.systemInfo = this.$getSystemInfo()
				this.isSwitchRole = this.systemInfo.isSwitchRole
			},
			visibleChange(val) {
				this.show = val
				if(val) {
					this.resourceOptionsFun('')
					this.getSubSystemList() // 获取子系统
					this.title = this.$t('components.handleResourceBatch.batchAssignDataGroup')
				}
			},
			checkDateValid(param) {
				this.showError = !((this.dataForm.startTm && this.dataForm.endTm && this.dataForm.dataGroupName))
				if(this.dataForm.startTm != '' && this.dataForm.endTm != '' && param) {
					if(this.dataForm.startTm > this.dataForm.endTm) {
						this.$message({
							message: this.$t('common.conmareEndTimeTip'),
							type: 'warning'
						})
						this.dataForm[param] = ''
					}
				}
			},
			/**
			 * @author：xmj
			 * @function:获取子系统列表
			 */
			async getSubSystemList(val) {
				this.subsysTemOptions = await this.$getSubSystemList(val)
			},
			handleSelectSubsys(item) { // 选择子系统时查角色
				this.dataForm.subsysCode = item.value
				this.dataForm.roleName = ''
				this.getroleList('')
			},
			async getroleList(val) { // 根据子系统编码查角色
				this.roleNameOptions = await this.$getroleListFun(val, this.dataForm.subsysCode, this.dataForm.byAccountId)
			},
			async resourceOptionsFun(queryString) { // 资源名称模糊搜索
				this.resourceOptions = await this.$resourceOptionsFun(queryString, this.dataForm.roleName)
			},
			handleSelectResource(item) { // 选择资源后
				this.dataForm.resourceCode = item.code
				this.dataForm.resourceId = item.id
				this.dataForm.resourceName = item.label
				this.dataForm.customDatagroup = item.customDatagroup
				this.dataForm.systemId = item.systemId
				this.dataForm.paramStruct = item.paramStruct
				this.dataForm.paramUrl = item.paramUrl
				this.dataForm.paramType = item.paramType
				this.dataForm.ownerSysId = item.ownerSysId
				this.dataForm.dataGroupName = ''
				if(this.dataForm.dataGroupType) {
					this.dataGroupNameOptionsFun('')
				}
			},
			// 根据资源id查数据组
			async dataGroupNameOptionsFun(queryString) {
				this.dataGroupArr = await this.$dataGroupNameOptionsFun(queryString, this.dataForm.resourceId)
			},
			selectAddListChange(val) { // 百源账号列表勾选
				this.addSelectMultipleSelection = val
			},
			save() {
				var that = this
				this.$refs['dataForm'].validate((valid) => {
					if(valid) {
						if(!that.dataForm.endTm || !that.dataForm.startTm) { // 未填写失效时间,预申请未填写开始时间
							that.showError = true
						} else if(that.addSelectMultipleSelection.length < 1) { // 未勾选角色
							MessageBox({
								message: this.$t('common.emptyTip'),
								confirmButtonText: this.$t('common.iknow')
							})
						} else { // 页面值校验通过
							if(!that.dataForm.dataGroupIdList && that.dataForm.dataGroupType == 2) {
								MessageBox({
									message: this.$t('components.handleResourceBatch.creatAutoDifinedData'),
									confirmButtonText: this.$t('common.iknow')
								})
								return
							}
							that.$emit('dataHandleBatchSave', that.dataForm, that.addSelectMultipleSelection)
						}
					} else {
						if(!that.dataForm.endTm) { // 未填写失效时间
							that.showError = true
						} else if(!that.dataForm.startTm) { // 预申请未填写开始时间
							that.showError = true
						} else if(!that.dataForm.dataGroupName) { // 预申请未填写开始时间
							that.showError = true
							return
						}
						return false
					}
				})
			},
			getFocusChange(param) {
				// 校验所填写工号是否合法
				var that = this
				this.$httpExt().post('/dev-basp-user/account/selectInvalidUsername', { // 查询填写的账号中不合法的账号
					usernames: this.accountText
				}).then(function(response) {
					if(response.result.length == 0 && param == 'submit') { // 没有不合法工号
						that.submitAccount()
					} else {
						var arr = that.accountText.split(',')
						for(var i = 0; i < arr.length; i++) {
							var tempindex = response.result.indexOf(arr[i])
							if(tempindex > -1) {
								arr[i] = {
									label: arr[i],
									flag: false
								}
							} else {
								arr[i] = {
									label: arr[i],
									flag: true
								}
							}
						}
						that.accountTextList = arr
						that.getFocusVisible = false
					}
				}, function(response) {
					that.accountTextList = that.accountText.split(',')
					that.getFocusVisible = false
					Message({
						message: response.msg ? response.msg : this.$t('common.exceptionWornText'),
						type: 'warning'
					})
				})
			},
			submitAccount() { // 提交后台
				var that = this
				that.$httpExt().post('/dev-basp-user/account/queryAccountInfoList', {
					usernames: this.accountText
				}).then(function(response) {
					var arr = response.result
					arr = arr.filter(item => {
						var temp = true
						for(var i = 0; i < that.datatableList.length; i++) {
							if(item.byAccountId == that.datatableList[i].byAccountId) {
								temp = false
								break
							}
						}
						return temp
					})
					that.datatableList = that.datatableList.concat(arr)
					that.addAccountVisible = false
				}, function(response) {
					Message({
						message: response.msg ? response.msg : this.$t('common.exceptionWornText'),
						type: 'warning'
					})
				})
			},
			saveAccount() {
				if(!this.accountText) {
					this.$message({
						message: this.$t('components.handleResourceBatch.inputAccount'),
						type: 'warning'
					})
				} else { // 校验
					this.getFocusChange('submit')
				}
			},
			removeSelect() { // 将已勾选的选项删除
				if(this.addSelectMultipleSelection.length) {
					for(var i = 0; i < this.addSelectMultipleSelection.length; i++) {
						var index = this.datatableList.indexOf(this.addSelectMultipleSelection[i])
						if(index > -1) {
							this.datatableList.splice(index, 1)
						}
					}
					this.dataForm.dataGroupIdList = null
				}
			},
			reset() { // 重置模态框数据
				this.$refs['dataForm'].resetFields() // 重置表单
				this.dataForm = {
					subsysName: '',
					roleName: '',
					resourceName: '',
					endTm: '',
					startTm: '',
					dataGroupName: '',
					dataGroupType: '1'
				}
				this.datatableList = []
				this.addSelectMultipleSelection = []
				this.roleNameOptions = []
				this.subsysTemOptions = []
				this.showError = false
			},
			closeDiolag() {
				this.reset()
				this.$emit('close')
			},
			autoDefined() { // 自定义按钮
				this.$refs['dataForm'].validate((valid) => { // 根据当前条件查询自定义数据组若无则需要新建
					if(valid) {
						if(this.addSelectMultipleSelection.length) {
							var urlH = '/dev-basp-user/accountDataGroup/selectCustomDateGroupList'
							var userList = []
							for(var i = 0; i < this.addSelectMultipleSelection.length; i++) {
								userList.push({
									username: this.addSelectMultipleSelection[i].byAccountName,
									byAccountId: this.addSelectMultipleSelection[i].byAccountId
								})
							}
							var param = {
								resourceId: this.dataForm.resourceId,
								resourceName: this.dataForm.resourceName,
								queryList: userList
							}
							this.$httpExt().post(urlH, param)
								.then((response) => {
									this.dataForm.dataGroupIdList = response.result
									this.dataForm.dataGroupId = response.result[0].dataGroupId
									this.dataForm.dataGroupName = response.result[0].dataGroupName || ''
									this.autoDefinedVisible = true
								}, (response) => {
									Notification.error({
										title: this.$t('common.exception'),
										message: response.msg ? response.msg : this.$t('common.exceptionWornText')
									})
								})
						} else {
							Message({
								message: this.$t('components.handleResourceBatch.selectAccount'),
								type: 'warning'
							})
						}
					} else {
						return false
					}
				})
			},
			customDialogSave(dataSourceRow, currentCheckedNodes) { // 创建了自定义数据组后保存
				this.saveResourceChecked(dataSourceRow, currentCheckedNodes)
			},
			saveResourceChecked(dataSourceRow, currentCheckedNodes) { // 提交该自定义数据组的勾选
				var codeList = []
				for(var i = 0; i < currentCheckedNodes.length; i++) {
					codeList.push(currentCheckedNodes[i].code)
				}
				var datagroupList = []
				for(var k = 0; k < this.dataForm.dataGroupIdList.length; k++) {
					datagroupList.push({
						dataGroupId: this.dataForm.dataGroupIdList[k].dataGroupId,
						resourceId: dataSourceRow.resourceId
					})
				}
				var param = {
					dataGroupParamsList: datagroupList,
					codeList: codeList,
					paramUrl: dataSourceRow.paramUrl,
				}
				var urlH = "/dev-basp-user/accountDataGroup/saveBatchCustomDataGroup"
				let loadingInstance = Loading.service({
					fullscreen: true
				})
				this.$httpExt().post(urlH, param)
					.then((response) => {
						loadingInstance.close()
						this.$message({
							message: response.msg ? response.msg : this.$t('components.handleResourceBatch.appendSuccess'),
							type: 'success'
						})
						this.autoDefinedVisible = false
					}, (response) => {
						loadingInstance.close()
						Notification.error({
							title: this.$t('common.exception'),
							message: response.msg ? response.msg : this.$t('common.exceptionWornText')
						})
					})
			}
		}
	}
</script>
<style lang="less" scoped>
	.handleDialog {
		min-width: 1100px;
		p {
			display: block;
			-webkit-margin-before: 1em;
			-webkit-margin-after: 1em;
			-webkit-margin-start: 0px;
			-webkit-margin-end: 0px;
		}
		.alignC {
			text-align: center;
			margin-bottom: 10px;
		}
		.addtionTableSpan {
			display: inline-block;
			width: auto;
			height: 15px;
			padding: 0px 5px;
			line-height: 15px;
			text-align: center;
			border: 1px solid #ccc;
			border-radius: 2px;
		}
	}
	
	p {
		display: block;
		-webkit-margin-before: 1em;
		-webkit-margin-after: 1em;
		-webkit-margin-start: 0px;
		-webkit-margin-end: 0px;
	}
</style>